<?php
/**
 * ShopEx licence
 *
 * @copyright  Copyright (c) 2005-2010 ShopEx Technologies Inc. (http://www.shopex.cn)
 * @license  http://ecos.shopex.cn/ ShopEx License
 */

class b2c_coupon_mem {


    public function __construct() {
        $this->app = app::get('b2c');
    }


    public function exchange($id=0, $m_id=0, $point=0,&$params) {

        $id = (int)$id;
        if( empty($id) || empty($m_id) ) return false;

        $o = $this->app->model('coupons');
        $arr = $o->dump($id);
        if( !$arr['rule']['rule_id'] ) return false;
        if($arr['cpns_status'] === '0') return false;
        $arr_rule_order = $this->app->model('sales_rule_order')->dump( $arr['rule']['rule_id'] );

        if( !$arr_rule_order || $arr_rule_order['to_time']<=time() ) return false;
        if( empty($arr) ) return false;
        if( $point<$arr['cpns_point'] ) return false;

        // begin 目前领取出现券码重复, 排查原因是并发引起的 add by Smith at 2017-11-2
        $this->_dealCouponCode($arr, $memcCode, $cpnsGenQuantity);
        //end
        //
        $arr_m_c['memc_code'] = $memcCode;
        if(!$o->isDownloadAble($arr_m_c['memc_code'])) return false; //是否可下载 B类
        $arr['cpns_gen_quantity'] = $cpnsGenQuantity;
        $o->save($arr);
        $arr_m_c['cpns_id'] = $arr['cpns_id'];
        $arr_m_c['member_id'] = $m_id;
        $arr_m_c['memc_used_times'] = 0;
        $arr_m_c['memc_gen_time'] = time();
        $params['cpns_point'] = $arr['cpns_point'];
        $params['memc_code'] = $arr_m_c['memc_code'];
        return $this->app->model('member_coupon')->save($arr_m_c);
    }

    public function exchange_delete( $params ) {
        if( $params['memc_code'] )
            $this->app->model('member_coupon')->delete($params);
    }


    public function obtain($id=0, $m_id=0,&$params){
        $id = (int)$id;
        if( empty($id) || empty($m_id) ) return false;

        $o = $this->app->model('coupons');
        $arr = $o->dump($id);
        if( !$arr['rule']['rule_id'] ) return false;
        if($arr['cpns_status'] === '0') return false;
        $arr_rule_order = $this->app->model('sales_rule_order')->dump( $arr['rule']['rule_id'] );

        if( !$arr_rule_order || $arr_rule_order['to_time']<=time() ) return false;
        if( empty($arr) ) return false;

        // begin 目前领取出现券码重复, 排查原因是并发引起的 add by Smith at 2017-11-2
        if(!$this->_dealCouponCode($arr, $memcCode, $cpnsGenQuantity)){
           return false;
        }
        //end

        $arr_m_c['memc_code'] = $memcCode;
        if(!$o->isDownloadAble($arr_m_c['memc_code'])) return false; //是否可下载 B类
        $arr['cpns_gen_quantity'] = $cpnsGenQuantity;
        $o->save($arr);
        $arr_m_c['cpns_id'] = $arr['cpns_id'];
        $arr_m_c['member_id'] = $m_id;
        $arr_m_c['memc_used_times'] = 0;
        $arr_m_c['memc_gen_time'] = time();
        $params['memc_code'] = $arr_m_c['memc_code'];
        return $this->app->model('member_coupon')->save($arr_m_c);
    }
    
    /**
     * 生成券号(主要为解决重复券号的问题)
     */
    private function _dealCouponCode($arr, &$memcCode, &$cpnsGenQuantity)
    {
        $couponMdl = $this->app->model('coupons');
        $cpnsGenQuantity = $arr['cpns_gen_quantity'];
        $flag = true;
        
        while(1){
            ++$cpnsGenQuantity;
            $memcCode = $couponMdl->_makeCouponCode($cpnsGenQuantity, $arr['cpns_prefix'], $arr['cpns_key']);
            if(!$memcCode){
                $flag = false;
                break;
            }
            // 校验券号是否使用过
            if(!base_kvstore::instance('b2c_member_coupon')->fetch('memcCode_'.$memcCode)){
                break;
            }
        }
        // 把生成的券号存储到KV
        base_kvstore::instance('b2c_member_coupon')->store('memcCode_'.$memcCode, $memcCode);
        return $flag;
    }

    public function get_list_m($m_id=0,$nPage=null,$coupon_status=null) {
        if( empty($m_id) ) return false;
         
        $filter = array('member_id'=>$m_id);
//        $filter['disabled'] = 'false';
        $filter['memc_isvalid'] = 'true';
        if($nPage){
            $pageLimit = 10;
            $offset = $pageLimit*($nPage-1);
        }else{
            $offset = 0;
            $pageLimit = -1;
        }
        
      
        $arr = $this->app->model('member_coupon')->_get_list('*', $filter,$offset,$pageLimit);
        // echo "<pre>";
        // print_r($arr);exit;
        //已使用的优惠券
        if($coupon_status=="used")
        {
            $arr = $this->_isUsedCoupon($arr);
        }
        //已过期的优惠券
        if($coupon_status=="expire")
        {
            $arr = $this->_expireCoupon($arr);
        }

        return $arr;
    }


    public function get_coupons($m_id){
        if( empty($m_id) ) return false;
        $filter = array('member_id'=>$m_id);
        $filter['memc_isvalid'] = 'true';

        $arr = $this->app->model('member_coupon')->_get_list('*', $filter);
        return $arr;
    }
    public function get_list() {
        $sql = "SELECT * FROM `sdb_b2c_coupons` WHERE cpns_point is not null AND cpns_status='1'";
        $arr = $this->app->model('coupons')->db->select($sql);
        foreach( $arr as $key => &$row ) {
            if(empty($row['rule_id'])) continue;
            $arr_rule_info = $this->app->model('sales_rule_order')->dump($row['rule_id'], 'from_time,to_time,member_lv_ids');
            if( $arr_rule_info['to_time']<=time() ) unset($arr[$key] );
            $row['time'] = $arr_rule_info;
        }
        return $arr;
    }


    /**
     * member_id 与 memc_code 组成唯一标识
     * 其他会员适用该优惠号码时修改表数据处理（根据号码查询信息、修改)
     **/
    public function use_c($memc_code ='', $uid=null, $order_id =null, $status='busy' ) {
        if( empty($uid) ) return false;
        if( empty($memc_code) ) return false;
        $o = $this->app->model('member_coupon');
        $couponFlag = $this->app->model('coupons')->getFlagFromCouponCode($memc_code);

        if( strtolower($couponFlag)!='b' ) return false;
        $coupons = $this->app->model('coupons')->getCouponByCouponCode($memc_code);
        $coupons = $coupons[0];
        $arr['memc_code'] = $memc_code;
        $arr['memc_used_times'] = $status == 'false' ? 0 : 1;
        $arr['memc_gen_orderid'] = $order_id;
        $arr['disabled'] = $status;
        $arr['cpns_id'] = $coupons['cpns_id'];
        $m_coupon = $o->getList( '*',array('memc_code'=>$memc_code) );
        if( !$m_coupon ) return false;
        $arr['member_id'] = $m_coupon[0]['member_id'];
        return $o->save($arr);
    }

    //已使用的优惠券
    private function _isUsedCoupon($arr)
    {
         $data = array();
         foreach ($arr as $key => $value)
          {
               if($value['memc_used_times']>0)
               {
                   $data[$key] = $value;
                   $data[$key]['status'] = "used";
               }

          }
          return $data;
    }

   //已过期的优惠券
   private function _expireCoupon($arr)
   {
         $data = array();
         foreach ($arr as $key => $value)
          {
               $from_time = $value['time']['from_time'];
               $to_time = $value['time']['to_time'];
               if($to_time<time())
               {
                   $data[$key] = $value;
                   $data[$key]['status'] = "expire";
               }

          }
        
          return $data;
   }

    //可使用未过期的优惠券
    private function _filteUnsedCoupons($arr)
    {
        $data = array();
        foreach ($arr as $key => $value)
        {
            $from_time = $value['time']['from_time'];
            $to_time = $value['time']['to_time'];
            if($from_time>time())
            {
                $data[$key] = $value;
                $data[$key]['status'] = "exceeded";
            }

        }

        return $data;
    }

   //wap端优惠券分页重新组织数据
   public function getMemCoupos($m_id=0,$coupon_status=null){
     
        if( empty($m_id) ) return false;
         
        $filter = array('member_id'=>$m_id);
        $filter['memc_isvalid'] = 'true';
        $arr = $this->app->model('member_coupon')->_get_list('*', $filter);
        //过滤后台删除的优惠券
        $data = $this->_filterDeletedCoupons($arr);


          //已使用的优惠券
        if($coupon_status=="used")
        {
            $coupons = $this->_isUsedCoupon($data);
        }
        //已过期的优惠券
        if($coupon_status=="expire")
        {
            $coupons = $this->_expireCoupon($data);
        }

        //可使用优惠券剔除已过期的优惠券
        if($coupon_status == 'unsed'){
            $coupons = $this->_filteExpireCoupons($data);
        }

       //可使用优惠券剔除未过期的优惠券
       if($coupon_status == 'exceeded'){
           $coupons = $this->_filteUnsedCoupons($data);
       }

        return $coupons;
     
   }


    //可使用的优惠券过滤已经过期的
    private function _filteExpireCoupons($aData){

        $time = time();
        $data = array();
        if($aData){
             foreach ($aData as $key => $value) {
                 if($time<=$value['time']['to_time'] && $time>=$value['time']['from_time']){
                     $data[$key] = $value;
                  }
             }
        }
        return $data;
       
    }

    //过滤后台已经删除的优惠券
    private function _filterDeletedCoupons($arr){
        
        $modelCoupons = app::get('b2c')->model('coupons');
        //取出没删除的优惠券
        $cpns = $modelCoupons->getList('cpns_id');
        $cpns_id = array();
        foreach ($cpns as $key => $value) {
             $cpns_id[] = $value['cpns_id'];
        }

        foreach ($arr as $k => $coupon_info) {
            if(!in_array($coupon_info['cpns_id'],$cpns_id)){
                 unset($arr[$k]);
            }
        }
        return $arr;


    }

}

